package com.sanxiang.interceptor;


import cn.hutool.core.util.StrUtil;
import com.sanxiang.entity.ManagerTable;
import com.sanxiang.exception.CustomException;
import com.sanxiang.mapper.ManagerTableMapper;
import com.sanxiang.service.RedisService;
import com.sanxiang.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * RequestInterceptor
 */
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    // 自动续时的期限
    private final Long DURATION = 1 * 12 * 60 * 60 * 1000L;

    /**
     * 忽略拦截的url
     */
    private final String[] urls = {
            "/manager/login"
    };

    @Resource
    private ManagerTableMapper managerTableMapper;

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {


        String url = request.getRequestURI();
        // 获取参数中的token验证相关参数
        String token = request.getHeader("token"); //前端vue将token添加在请求头中
        // 遍历需要忽略拦截的路径
        for (String item : this.urls) {
            if (item.equals(url)) {
                log.info("无须拦截的url:{}", item);
                return true;
            }
        }
        // 查询验证token
        if (StrUtil.isBlank(token)) {
            throw new CustomException(401, "未获取到token, 请重新登录");
        }

        // 验证 token
        Boolean res = TokenUtil.verify(token);
        if (!res) {
            throw new CustomException(401, "token不合法");
        }

        ManagerTable managerTable = managerTableMapper.selectById(TokenUtil.getId(token));
        if (managerTable == null) {
            throw new CustomException(401, "用户不合法");
        }

        //2.判断是否需要续期
        if (redisService.getExpireTime(String.valueOf(managerTable.getManagerId())) < DURATION) {
            redisService.set(String.valueOf(managerTable.getManagerId()), token);
            log.error("update token info, id is:{}, token info is:{}", managerTable.getManagerId(), token);
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // System.out.println("处理请求完成后视图渲染之前的处理操作");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        // System.out.println("视图渲染之后的操作");
    }

}
